<template>
  <view class="orders-admin-page">
    <!-- 权限提示 -->
    <view v-if="isPersonalView" class="permission-notice">
      <text class="notice-text">👤 当前显示个人订单</text>
      <text class="notice-desc">如需管理所有订单，请使用管理员账户登录</text>
    </view>

    <!-- 统计卡片 -->
    <view class="stats-section">
      <view class="stats-grid">
        <view class="stat-card">
          <view class="stat-number">{{ stats.total || 0 }}</view>
          <view class="stat-label">总订单</view>
        </view>
        <view class="stat-card">
          <view class="stat-number">{{ stats.pending || 0 }}</view>
          <view class="stat-label">待处理</view>
        </view>
        <view class="stat-card">
          <view class="stat-number">{{ stats.completed || 0 }}</view>
          <view class="stat-label">已完成</view>
        </view>
        <view class="stat-card">
          <view class="stat-number">{{ stats.cancelled || 0 }}</view>
          <view class="stat-label">已取消</view>
        </view>
      </view>
    </view>

    <!-- 搜索和筛选 -->
    <view class="filter-section">
      <view class="search-box">
        <input v-model="searchKeyword" placeholder="搜索订单号或用户昵称" class="search-input" @confirm="handleSearch" />
        <view class="search-btn" @click="handleSearch">
          <text>搜索</text>
        </view>
      </view>

      <view class="filter-tabs">
        <view class="tab-item" :class="{ active: activeTab === 'all' }" @click="switchTab('all')">
          全部
        </view>
        <view class="tab-item" :class="{ active: activeTab === 'pending' }" @click="switchTab('pending')">
          待处理
        </view>
        <view class="tab-item" :class="{ active: activeTab === 'processing' }" @click="switchTab('processing')">
          处理中
        </view>
        <view class="tab-item" :class="{ active: activeTab === 'completed' }" @click="switchTab('completed')">
          已完成
        </view>
        <view class="tab-item" :class="{ active: activeTab === 'cancelled' }" @click="switchTab('cancelled')">
          已取消
        </view>
      </view>
    </view>

    <!-- 订单列表 -->
    <view class="orders-list">
      <view class="order-card" v-for="order in filteredOrders" :key="order.id" @click="viewOrderDetail(order.id)">
        <!-- 订单头部 -->
        <view class="order-header">
          <view class="order-info">
            <view class="order-number">订单号: {{ order.orderNumber || order.order_no }}</view>
            <view class="order-time">{{ formatTime(order.createdAt || order.created_at) }}</view>
          </view>
          <view class="order-status" :class="['status-' + order.status]">
            {{ getStatusText(order.status) }}
          </view>
        </view>

        <!-- 用户信息 -->
        <view class="user-section">
          <view class="user-info">
            <text class="user-label">用户:</text>
            <text class="user-name">{{ getUserName(order) }}</text>
          </view>
          <view class="user-info">
            <text class="user-label">手机:</text>
            <text class="user-phone">{{ getUserPhone(order) }}</text>
          </view>
        </view>

        <!-- 商品信息 -->
        <view class="products-section">
          <view class="section-title">商品清单</view>
          <view class="product-item" v-for="item in getOrderItems(order)" :key="item.id">
            <view class="product-info">
              <text class="product-name">{{ getProductName(item) }}</text>
              <text class="product-spec">{{ getProductSpec(item) }}</text>
            </view>
            <view class="product-quantity">x{{ item.quantity }}</view>
            <view class="product-points">{{ item.pointsUsed || item.unit_points }}积分</view>
          </view>
        </view>

        <!-- 订单汇总 -->
        <view class="order-summary">
          <view class="summary-row">
            <text class="summary-label">商品数量:</text>
            <text class="summary-value">{{ getTotalQuantity(order) }}</text>
          </view>
          <view class="summary-row">
            <text class="summary-label">订单类型:</text>
            <text class="summary-value">{{ getOrderType(order) }}</text>
          </view>
          <view v-if="order.reservationCode || order.reservation_code" class="summary-row">
            <text class="summary-label">预约码:</text>
            <text class="summary-value reservation-code">{{ order.reservationCode || order.reservation_code }}</text>
          </view>
          <view class="summary-row total-row">
            <text class="summary-label">总积分:</text>
            <text class="summary-value total-points">{{ order.totalPoints || order.total_points }}积分</text>
          </view>
        </view>

        <!-- 操作按钮 -->
        <view class="order-actions">
          <button v-if="!isPersonalView && order.status === 'pending'" class="action-btn process-btn"
            @click.stop="updateOrderStatus(order, 'processing')">
            开始处理
          </button>
          <button v-if="!isPersonalView && order.status === 'processing'" class="action-btn complete-btn"
            @click.stop="updateOrderStatus(order, 'completed')">
            完成订单
          </button>
          <button v-if="!isPersonalView && (order.status === 'pending' || order.status === 'processing')"
            class="action-btn cancel-btn" @click.stop="updateOrderStatus(order, 'cancelled')">
            取消订单
          </button>
          <button class="action-btn detail-btn" @click.stop="viewOrderDetail(order.id)">
            查看详情
          </button>
        </view>
      </view>
    </view>

    <!-- 加载状态 -->
    <view v-if="loading" class="loading-section">
      <text>加载中...</text>
    </view>

    <!-- 空状态 -->
    <view v-if="!loading && filteredOrders.length === 0" class="empty-section">
      <text class="empty-text">暂无订单数据</text>
      <text class="empty-tip">订单数据将在用户下单后显示</text>
    </view>

    <!-- 分页 -->
    <view v-if="pagination.total > pagination.limit" class="pagination-section">
      <view class="pagination-info">
        <text>共 {{ pagination.total }} 条，第 {{ pagination.page }} / {{ pagination.pages }} 页</text>
      </view>
      <view class="pagination-controls">
        <button class="page-btn" :disabled="pagination.page <= 1" @click="changePage(pagination.page - 1)">
          上一页
        </button>
        <button class="page-btn" :disabled="pagination.page >= pagination.pages"
          @click="changePage(pagination.page + 1)">
          下一页
        </button>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      loading: false,
      activeTab: 'all',
      searchKeyword: '',
      orders: [],
      isPersonalView: false, // 标记是否为个人视图
      roleChecked: false, // 标记是否已检查用户角色
      stats: {
        total: 0,
        pending: 0,
        processing: 0,
        completed: 0,
        cancelled: 0
      },
      pagination: {
        page: 1,
        limit: 10,
        total: 0,
        pages: 0
      }
    }
  },

  computed: {
    filteredOrders() {
      let filtered = this.orders

      // 按状态筛选
      if (this.activeTab !== 'all') {
        filtered = filtered.filter(order => order.status === this.activeTab)
      }

      // 按关键词搜索
      if (this.searchKeyword) {
        const keyword = this.searchKeyword.toLowerCase()
        filtered = filtered.filter(order => {
          const orderNumber = (order.orderNumber || order.order_no || '').toLowerCase()
          const userName = this.getUserName(order).toLowerCase()
          return orderNumber.includes(keyword) || userName.includes(keyword)
        })
      }

      return filtered
    }
  },

  async onLoad() {
    await this.checkUserRole()
    this.loadOrders()
    this.loadStatistics()
  },

  onPullDownRefresh() {
    this.refreshData()
  },

  methods: {
    // 检查用户角色
    async checkUserRole() {
      try {
        const token = uni.getStorageSync('token')
        const userInfo = uni.getStorageSync('userInfo')

        // 如果本地存储中有用户信息且不是管理员，直接设置为个人视图
        if (userInfo && userInfo.role !== 'admin') {
          this.isPersonalView = true
          return
        }

        // 尝试访问管理员接口来验证权限
        const testRes = await uni.request({
          url: 'http://localhost:3000/api/admin/orders/analytics/overview',
          method: 'GET',
          header: {
            'Authorization': `Bearer ${token}`
          }
        })

        // 如果成功访问，说明有管理员权限
        if (testRes.statusCode === 200 && testRes.data && testRes.data.success) {
          this.isPersonalView = false
        } else {
          this.isPersonalView = true
        }
      } catch (error) {
        // 如果访问失败，设置为个人视图
        console.log('管理员权限检查失败，切换到个人视图:', error)
        this.isPersonalView = true
      } finally {
        this.roleChecked = true
      }
    },

    // 加载订单列表
    async loadOrders() {
      try {
        this.loading = true
        const token = uni.getStorageSync('token')

        // 构建查询参数，过滤掉undefined值
        const params = {}
        params.page = this.pagination.page
        params.limit = this.pagination.limit
        
        if (this.activeTab !== 'all') {
          params.status = this.activeTab
        }
        
        if (this.searchKeyword && this.searchKeyword.trim()) {
          params.search = this.searchKeyword.trim()
        }

        // 根据用户权限选择不同的API端点
        const apiUrl = this.isPersonalView
          ? 'http://localhost:3000/api/orders'
          : 'http://localhost:3000/api/admin/orders'

        const res = await uni.request({
          url: apiUrl,
          method: 'GET',
          header: {
            'Authorization': `Bearer ${token}`
          },
          data: params
        })

        if (res.data && res.data.success) {
          this.orders = res.data.data.orders || []
          const pagination = res.data.data.pagination || {}
          this.pagination = {
            page: pagination.current || 1,
            limit: pagination.pageSize || 10,
            total: pagination.totalItems || 0,
            pages: pagination.total || 0
          }

          // 如果是第一次成功加载且使用的是个人接口，显示提示
          if (this.isPersonalView && this.pagination.page === 1) {
            uni.showToast({
              title: '显示个人订单',
              icon: 'none',
              duration: 1500
            })
          }
        } else {
          throw new Error(res.data?.message || '获取订单失败')
        }
      } catch (error) {
        console.error('获取订单失败:', error)

        // 如果是管理员接口失败，尝试降级到个人接口
        if (!this.isPersonalView && (error.statusCode === 403 || error.statusCode === 401 || 
            (error.data && error.data.message && (error.data.message.includes('权限') || error.data.message.includes('unauthorized'))))) {
          console.log('管理员接口访问失败，降级到个人接口')
          this.isPersonalView = true
          // 递归调用，使用个人接口重试
          return this.loadOrders()
        } else {
          uni.showToast({
            title: error.data?.message || error.errMsg || '获取订单失败',
            icon: 'none'
          })
        }
      } finally {
        this.loading = false
        uni.stopPullDownRefresh()
      }
    },

    // 加载统计数据
    async loadStatistics() {
      try {
        const token = uni.getStorageSync('token')

        // 根据用户权限选择不同的API端点
        const apiUrl = this.isPersonalView
          ? 'http://localhost:3000/api/orders/statistics/summary'
          : 'http://localhost:3000/api/admin/orders/analytics/overview'

        const res = await uni.request({
          url: apiUrl,
          method: 'GET',
          header: {
            'Authorization': `Bearer ${token}`
          }
        })

        if (res.data && res.data.success) {
          const data = res.data.data || {}

          if (this.isPersonalView) {
            // 个人统计数据格式
            this.stats = {
              total: data.totalOrders || 0,
              pending: data.pendingOrders || 0,
              processing: 0, // 用户统计中没有processing状态
              completed: data.completedOrders || 0,
              cancelled: data.cancelledOrders || 0
            }
          } else {
            // 管理员统计数据格式 - 适配新的API响应格式
            this.stats = {
              total: data.totalOrders || 0,
              pending: data.pendingOrders || 0,
              processing: data.processingOrders || 0,
              completed: data.completedOrders || 0,
              cancelled: data.cancelledOrders || 0
            }
          }
        } else {
          throw new Error(res.data?.message || '获取统计数据失败')
        }
      } catch (error) {
        console.error('获取统计数据失败:', error)

        // 如果是管理员接口失败，尝试降级到个人接口
        if (!this.isPersonalView && (error.statusCode === 403 || error.statusCode === 401 || 
            (error.data && error.data.message && (error.data.message.includes('权限') || error.data.message.includes('unauthorized'))))) {
          console.log('管理员统计接口访问失败，降级到个人接口')
          this.isPersonalView = true
          // 递归调用，使用个人接口重试
          return this.loadStatistics()
        } else {
          console.log('统计数据获取失败，使用本地计算:', error)
          this.calculateLocalStats()
        }
      }
    },



    // 计算本地统计
    calculateLocalStats() {
      this.stats = {
        total: this.orders.length,
        pending: this.orders.filter(o => o.status === 'pending').length,
        processing: this.orders.filter(o => o.status === 'processing').length,
        completed: this.orders.filter(o => o.status === 'completed').length,
        cancelled: this.orders.filter(o => o.status === 'cancelled').length
      }
    },

    // 刷新数据
    refreshData() {
      this.pagination.page = 1
      this.loadOrders()
      this.loadStatistics()
    },

    // 切换标签
    switchTab(tab) {
      this.activeTab = tab
      this.pagination.page = 1
      this.loadOrders()
    },

    // 搜索
    handleSearch() {
      this.pagination.page = 1
      this.loadOrders()
    },

    // 更新订单状态
    async updateOrderStatus(order, newStatus) {
      // 检查是否为个人视图，如果是则不允许操作
      if (this.isPersonalView) {
        uni.showModal({
          title: '权限不足',
          content: '当前为个人订单视图，无法修改订单状态。请使用管理员账户登录。',
          showCancel: false
        })
        return
      }

      try {
        const statusText = this.getStatusText(newStatus)
        const result = await uni.showModal({
          title: '确认操作',
          content: `确定要将订单状态更改为"${statusText}"吗？`
        })

        if (!result.confirm) return

        uni.showLoading({ title: '更新中...' })

        const token = uni.getStorageSync('token')
        const res = await uni.request({
          url: `http://localhost:3000/api/admin/orders/${order.id}/status`,
          method: 'PUT',
          header: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          },
          data: {
            status: newStatus,
            notes: `管理员操作：${statusText}`
          }
        })

        if (res.data.success) {
          uni.showToast({
            title: '状态更新成功',
            icon: 'success'
          })

          // 更新本地数据
          const index = this.orders.findIndex(o => o.id === order.id)
          if (index > -1) {
            this.orders[index].status = newStatus
          }

          this.loadStatistics()
        } else {
          throw new Error(res.data.message || '更新失败')
        }
      } catch (error) {
        console.error('更新订单状态失败:', error)
        uni.showToast({
          title: '更新失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    },

    // 查看订单详情
    viewOrderDetail(orderId) {
      uni.navigateTo({
        url: `/pages/orders/detail?id=${orderId}`
      })
    },

    // 翻页
    changePage(page) {
      this.pagination.page = page
      this.loadOrders()
    },

    // 获取用户名
    getUserName(order) {
      if (!order) return '未知用户'
      if (order.User && order.User.nickname) {
        return order.User.nickname
      }
      if (order.user && order.user.nickname) {
        return order.user.nickname
      }
      if (order.User && order.User.phone) {
        return order.User.phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
      }
      if (order.user && order.user.phone) {
        return order.user.phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
      }
      return '未知用户'
    },

    // 获取用户手机
    getUserPhone(order) {
      if (!order) return '未绑定'
      if (order.User && order.User.phone) {
        return order.User.phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
      }
      if (order.user && order.user.phone) {
        return order.user.phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
      }
      return '未绑定'
    },

    // 获取订单项
    getOrderItems(order) {
      if (!order) return []
      return order.OrderItems || order.items || []
    },

    // 获取商品名称
    getProductName(item) {
      if (!item) return '未知商品'
      if (item.Product && item.Product.name) {
        return item.Product.name
      }
      if (item.product && item.product.name) {
        return item.product.name
      }
      if (item.productName) {
        return item.productName
      }
      if (item.product_name) {
        return item.product_name
      }
      return '未知商品'
    },

    // 获取商品规格
    getProductSpec(item) {
      if (!item) return ''
      if (item.Product && item.Product.specification) {
        return item.Product.specification
      }
      if (item.product && item.product.specification) {
        return item.product.specification
      }
      if (item.specification) {
        return item.specification
      }
      return ''
    },

    // 获取总数量
    getTotalQuantity(order) {
      if (!order) return 0
      const items = this.getOrderItems(order)
      return items.reduce((total, item) => total + (item.quantity || 0), 0)
    },

    // 获取订单类型
    getOrderType(order) {
      if (!order) return '普通订单'
      const typeMap = {
        'offline': '到店兑换',
        'online': '在线处理'
      }
      return typeMap[order.type] || '普通订单'
    },

    // 获取状态文本
    getStatusText(status) {
      if (!status) return '未知状态'
      const statusMap = {
        'pending': '待处理',
        'processing': '处理中',
        'completed': '已完成',
        'cancelled': '已取消'
      }
      return statusMap[status] || status
    },

    // 格式化时间
    formatTime(time) {
      if (!time) return ''
      try {
        const date = new Date(time)
        if (isNaN(date.getTime())) return ''
        return date.toLocaleString('zh-CN')
      } catch (error) {
        return ''
      }
    }
  }
}
</script>

<style scoped>
.orders-admin-page {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding: 20rpx;
}

.page-header {
  text-align: center;
  margin-bottom: 30rpx;
}

.page-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.stats-section {
  margin-bottom: 30rpx;
}

.stats-grid {
  display: flex;
  gap: 20rpx;
}

.stat-card {
  flex: 1;
  background: white;
  padding: 30rpx 20rpx;
  border-radius: 12rpx;
  text-align: center;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.stat-number {
  font-size: 32rpx;
  font-weight: bold;
  color: #007aff;
  margin-bottom: 10rpx;
}

.stat-label {
  font-size: 24rpx;
  color: #666;
}

.filter-section {
  background: white;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
}

.search-box {
  display: flex;
  align-items: center;
  margin-bottom: 30rpx;
}

.search-input {
  flex: 1;
  height: 70rpx;
  padding: 0 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
}

.search-btn {
  margin-left: 20rpx;
  padding: 20rpx 30rpx;
  background: #007aff;
  color: white;
  border-radius: 8rpx;
  font-size: 28rpx;
}

.filter-tabs {
  display: flex;
  gap: 20rpx;
}

.tab-item {
  flex: 1;
  padding: 20rpx;
  text-align: center;
  font-size: 26rpx;
  color: #666;
  background: #f8f8f8;
  border-radius: 8rpx;
}

.tab-item.active {
  color: #007aff;
  background: #e3f2fd;
}

.orders-list {
  margin-bottom: 30rpx;
}

.order-card {
  background: white;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20rpx;
}

.order-number {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 8rpx;
}

.order-time {
  font-size: 24rpx;
  color: #999;
}

.order-status {
  padding: 8rpx 16rpx;
  border-radius: 16rpx;
  font-size: 24rpx;
  color: white;
}

.status-pending {
  background: #ff9500;
}

.status-processing {
  background: #007aff;
}

.status-completed {
  background: #34c759;
}

.status-cancelled {
  background: #ff3b30;
}

.user-section {
  margin-bottom: 20rpx;
  padding: 20rpx;
  background: #f8f8f8;
  border-radius: 8rpx;
}

.user-info {
  display: flex;
  margin-bottom: 10rpx;
}

.user-info:last-child {
  margin-bottom: 0;
}

.user-label {
  width: 80rpx;
  font-size: 26rpx;
  color: #666;
}

.user-name,
.user-phone {
  font-size: 26rpx;
  color: #333;
}

.products-section {
  margin-bottom: 20rpx;
}

.section-title {
  font-size: 26rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 15rpx;
}

.product-item {
  display: flex;
  align-items: center;
  padding: 15rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.product-item:last-child {
  border-bottom: none;
}

.product-info {
  flex: 1;
}

.product-name {
  font-size: 26rpx;
  color: #333;
  margin-bottom: 5rpx;
}

.product-spec {
  font-size: 22rpx;
  color: #999;
}

.product-quantity {
  font-size: 24rpx;
  color: #666;
  margin: 0 20rpx;
}

.product-points {
  font-size: 24rpx;
  color: #007aff;
}

.order-summary {
  margin-bottom: 20rpx;
  padding-top: 20rpx;
  border-top: 1rpx solid #f0f0f0;
}

.summary-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10rpx;
}

.summary-row:last-child {
  margin-bottom: 0;
}

.total-row {
  font-weight: bold;
  padding-top: 10rpx;
  border-top: 1rpx solid #f0f0f0;
}

.summary-label {
  font-size: 26rpx;
  color: #666;
}

.summary-value {
  font-size: 26rpx;
  color: #333;
}

.reservation-code {
  color: #007aff;
  font-weight: bold;
}

.total-points {
  color: #ff4757;
  font-weight: bold;
}

.order-actions {
  display: flex;
  gap: 15rpx;
  justify-content: flex-end;
}

.action-btn {
  padding: 15rpx 25rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
  border: none;
}

.process-btn {
  background: #007aff;
  color: white;
}

.complete-btn {
  background: #34c759;
  color: white;
}

.cancel-btn {
  background: #ff3b30;
  color: white;
}

.detail-btn {
  background: #f8f8f8;
  color: #666;
}

.loading-section,
.empty-section {
  text-align: center;
  padding: 60rpx;
  color: #666;
}

.empty-text {
  font-size: 28rpx;
  margin-bottom: 10rpx;
}

.empty-tip {
  font-size: 24rpx;
  color: #999;
}

.pagination-section {
  background: white;
  border-radius: 12rpx;
  padding: 30rpx;
  text-align: center;
}

.pagination-info {
  margin-bottom: 20rpx;
  font-size: 26rpx;
  color: #666;
}

.pagination-controls {
  display: flex;
  justify-content: center;
  gap: 20rpx;
}

.page-btn {
  padding: 15rpx 30rpx;
  background: #007aff;
  color: white;
  border: none;
  border-radius: 8rpx;
  font-size: 26rpx;
}

.page-btn[disabled] {
  background: #ccc;
  color: #999;
}

.permission-notice {
  background: #e3f2fd;
  border: 1rpx solid #bbdefb;
  border-radius: 8rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
  text-align: center;
}

.notice-text {
  color: #1976d2;
  font-size: 26rpx;
  font-weight: bold;
  display: block;
  margin-bottom: 8rpx;
}

.notice-desc {
  color: #1976d2;
  font-size: 22rpx;
  opacity: 0.8;
}
</style>